package com.he.hsdyc.controller;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import me.chanjar.weixin.common.bean.WxJsapiSignature;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpMessageRouter;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.message.WxMpXmlMessage;
import me.chanjar.weixin.mp.bean.message.WxMpXmlOutMessage;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

@Api(value="微信接口核心类",description="微信接口核心方法",tags={"微信接口"})
@RestController
@RequestMapping(value="/core")
public class CoreController {
    protected Logger logger = LoggerFactory.getLogger(CoreController.class);

//    @Autowired
//    @Qualifier("wxMpService_user")
//    protected WxMpService wxMpService_user;
//
//    @Autowired
//    @Qualifier("wxMpService_teacher")
//    protected WxMpService wxMpService_teacher;
//
//    @Autowired
//    @Qualifier("wxMpService_parent")
//    protected WxMpService wxMpService_parent;

    @Autowired
    @Qualifier("wxMpService_parent2")
    protected WxMpService wxMpService_parent2;


//    @Autowired
//    @Qualifier("router_user")
//    private WxMpMessageRouter router_user;
//    @Autowired
//    @Qualifier("router_teacher")
//    private WxMpMessageRouter router_teacher;
//    @Autowired
//    @Qualifier("router_parent")
//    private WxMpMessageRouter router_parent;
    @Autowired
    @Qualifier("router_parent2")
    private WxMpMessageRouter router_parent2;


    /**
     * 服务器合法验证
     * @param signature
     * @param nonce
     * @param timestamp
     * @param echostr
     * @param usertype
     * @return
     */
    @RequestMapping(value = "/{usertype}",produces = "text/plain;charset=utf-8",method= RequestMethod.GET)
    public String weChatCore(String signature,String nonce,String timestamp,String echostr,@PathVariable String usertype){


        switch (usertype){
//            case "user":
//                if (!this.wxMpService_user.checkSignature(timestamp, nonce, signature)) {
//                    return "error";
//                }
//                break;
//            case "teacher":
//                if (!this.wxMpService_teacher.checkSignature(timestamp, nonce, signature)) {
//                    return "error";
//                }
//                break;
//            case "parent":
//                if (!this.wxMpService_parent.checkSignature(timestamp, nonce, signature)) {
//                    return "error";
//                }
//                break;
            case "parent2":
                if (!this.wxMpService_parent2.checkSignature(timestamp, nonce, signature)) {
                    return "error";
                }
                break;

        }




        return echostr;

    }

    /**
     * 接收微信推送
     * @param requestBody
     * @param signature
     * @param timestamp
     * @param nonce
     * @param encType
     * @param msgSignature
     * @param usertype
     * @return
     */
    @RequestMapping(value = "/{usertype}",produces = "application/xml; charset=UTF-8",method= RequestMethod.POST)
    public String post(@RequestBody String requestBody,
                       @RequestParam("signature") String signature,
                       @RequestParam("timestamp") String timestamp,
                       @RequestParam("nonce") String nonce,
                       @RequestParam(name = "encrypt_type",
                               required = false) String encType,
                       @RequestParam(name = "msg_signature",
                               required = false) String msgSignature,@PathVariable String usertype) {
        this.logger.info(
                "\n接收微信请求：[signature=[{}], encType=[{}], msgSignature=[{}],"
                        + " timestamp=[{}], nonce=[{}], requestBody=[\n{}\n] ",
                signature, encType, msgSignature, timestamp, nonce, requestBody);
        String out = null;


        switch (usertype){
//            case "user":
//                if (!this.wxMpService_user.checkSignature(timestamp, nonce, signature)) {
//                    throw new IllegalArgumentException("非法请求，可能属于伪造的请求！");
//                }
//
//
//                if (encType == null) {
//                    // 明文传输的消息
//                    WxMpXmlMessage inMessage = WxMpXmlMessage.fromXml(requestBody);
//                    WxMpXmlOutMessage outMessage = this.route(inMessage,usertype);
//                    if (outMessage == null) {
//                        return "";
//                    }
//
//                    out = outMessage.toXml();
//                } else if ("aes".equals(encType)) {
//                    // aes加密的消息
//                    WxMpXmlMessage inMessage = WxMpXmlMessage.fromEncryptedXml(
//                            requestBody, this.wxMpService_user.getWxMpConfigStorage(), timestamp,
//                            nonce, msgSignature);
//                    this.logger.debug("\n消息解密后内容为：\n{} ", inMessage.toString());
//                    WxMpXmlOutMessage outMessage = this.route(inMessage,usertype);
//                    if (outMessage == null) {
//                        return "";
//                    }
//
//                    out = outMessage
//                            .toEncryptedXml(this.wxMpService_user.getWxMpConfigStorage());
//                }
//
//                this.logger.debug("\n组装回复信息：{}", out);
//                break;
//            case "teacher":
//                if (!this.wxMpService_teacher.checkSignature(timestamp, nonce, signature)) {
//                    throw new IllegalArgumentException("非法请求，可能属于伪造的请求！");
//                }
//
//
//                if (encType == null) {
//                    // 明文传输的消息
//                    WxMpXmlMessage inMessage = WxMpXmlMessage.fromXml(requestBody);
//                    WxMpXmlOutMessage outMessage = this.route(inMessage,usertype);
//                    if (outMessage == null) {
//                        return "";
//                    }
//
//
//                    out = outMessage.toXml();
//                } else if ("aes".equals(encType)) {
//                    // aes加密的消息
//                    WxMpXmlMessage inMessage = WxMpXmlMessage.fromEncryptedXml(
//                            requestBody, this.wxMpService_teacher.getWxMpConfigStorage(), timestamp,
//                            nonce, msgSignature);
//                    this.logger.debug("\n消息解密后内容为：\n{} ", inMessage.toString());
//                    WxMpXmlOutMessage outMessage = this.route(inMessage,usertype);
//                    if (outMessage == null) {
//                        return "";
//                    }
//
//                    out = outMessage
//                            .toEncryptedXml(this.wxMpService_teacher.getWxMpConfigStorage());
//                }
//
//                this.logger.debug("\n组装回复信息：{}", out);
//                break;
//            case "parent":
//                if (!this.wxMpService_parent.checkSignature(timestamp, nonce, signature)) {
//                    throw new IllegalArgumentException("非法请求，可能属于伪造的请求！");
//                }
//
//
//                if (encType == null) {
//                    // 明文传输的消息
//                    WxMpXmlMessage inMessage = WxMpXmlMessage.fromXml(requestBody);
//                    WxMpXmlOutMessage outMessage = this.route(inMessage,usertype);
//                    if (outMessage == null) {
//                        return "";
//                    }
//
//                    out = outMessage.toXml();
//                } else if ("aes".equals(encType)) {
//                    // aes加密的消息
//                    WxMpXmlMessage inMessage = WxMpXmlMessage.fromEncryptedXml(
//                            requestBody, this.wxMpService_parent.getWxMpConfigStorage(), timestamp,
//                            nonce, msgSignature);
//                    this.logger.debug("\n消息解密后内容为：\n{} ", inMessage.toString());
//                    WxMpXmlOutMessage outMessage = this.route(inMessage,usertype);
//                    if (outMessage == null) {
//                        return "";
//                    }
//
//                    out = outMessage
//                            .toEncryptedXml(this.wxMpService_parent.getWxMpConfigStorage());
//                }
//
//                this.logger.debug("\n组装回复信息：{}", out);
//                break;
            case "parent2":
                if (!this.wxMpService_parent2.checkSignature(timestamp, nonce, signature)) {
                    throw new IllegalArgumentException("非法请求，可能属于伪造的请求！");
                }


                if (encType == null) {
                    // 明文传输的消息
                    WxMpXmlMessage inMessage = WxMpXmlMessage.fromXml(requestBody);
                    WxMpXmlOutMessage outMessage = this.route(inMessage,usertype);
                    if (outMessage == null) {
                        return "";
                    }

                    out = outMessage.toXml();
                } else if ("aes".equals(encType)) {
                    // aes加密的消息
                    WxMpXmlMessage inMessage = WxMpXmlMessage.fromEncryptedXml(
                            requestBody, this.wxMpService_parent2.getWxMpConfigStorage(), timestamp,
                            nonce, msgSignature);
                    this.logger.debug("\n消息解密后内容为：\n{} ", inMessage.toString());
                    WxMpXmlOutMessage outMessage = this.route(inMessage,usertype);
                    if (outMessage == null) {
                        return "";
                    }

                    out = outMessage
                            .toEncryptedXml(this.wxMpService_parent2.getWxMpConfigStorage());
                }

                this.logger.debug("\n组装回复信息：{}", out);
                break;

        }



        return out;
    }

    private WxMpXmlOutMessage route(WxMpXmlMessage message,String usertype) {
        try {
            switch (usertype){
//                case "user":
//                    return this.router_user.route(message);
//                case "teacher":
//                    return this.router_teacher.route(message);
//                case "parent":
//                    return this.router_parent.route(message);
                case "parent2":
                    return this.router_parent2.route(message);


            }

        } catch (Exception e) {
            this.logger.error(e.getMessage(), e);
        }

        return null;
    }


    @ApiOperation("生成JS-SDK")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "wechatType",
                    value = "微信端类型", dataType = "Integer",
                    required = true, paramType = "path"),
            @ApiImplicitParam(name = "url",
                    value = "页面地址", dataType = "String",
                    required = true, paramType = "form"),
    })
    @RequestMapping(value = "/{wechatType}/jssdk",method= RequestMethod.POST)
    @ResponseBody
    public WxJsapiSignature getJsSdkParam(@PathVariable Integer wechatType, String url, HttpServletResponse response){

        WxJsapiSignature result=null;
        try {
            switch (wechatType){
//                case 0:         //用户端
//                    result=wxMpService_user.createJsapiSignature(url);
//                    break;
//                case 1:         //教师端
//                    result=wxMpService_teacher.createJsapiSignature(url);
//                    break;
//                case 2:         //家长端
//                    result=wxMpService_parent.createJsapiSignature(url);
//                    break;
                case 3:         //YES家长端
                    result=wxMpService_parent2.createJsapiSignature(url);
                    break;

            }

        } catch (WxErrorException e) {
            e.printStackTrace();
        }

        response.addHeader("Access-Control-Allow-Origin","*");
        response.addHeader("Access-Control-Allow-Methods","*");
        response.addHeader("Access-Control-Max-Age","100");
        response.addHeader("Access-Control-Allow-Headers", "Content-Type");
        response.addHeader("Access-Control-Allow-Credentials","false");

        return result;

    }



    public  InputStream getInputStream(String urlStr){
        InputStream inputStream=null;
        HttpURLConnection httpURLConnection=null;
        try{
            URL url=new URL(urlStr);
            if(url!=null){
                httpURLConnection=(HttpURLConnection) url.openConnection();
                httpURLConnection.setConnectTimeout(3000);
                httpURLConnection.setRequestMethod("GET");
                int responseCode=httpURLConnection.getResponseCode();
                if(responseCode==200){
                    inputStream=httpURLConnection.getInputStream();
                }
            }


        }catch(Exception e){
            e.printStackTrace();
        }



        return inputStream;

    }










}
